package com.ljyh.cygnus.utils

import com.ljyh.cygnus.model.CommandOutput
import com.topjohnwu.superuser.Shell
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException


object RootCommandExecutor {
    suspend fun execute(vararg commands: String): CommandOutput {
        return suspendCancellableCoroutine { continuation ->
            val stdout = mutableListOf<String>()
            val stderr = mutableListOf<String>()

            // 先构造 Job，再入队得到 Future<Result>
            val job = Shell.cmd(*commands).to(stdout, stderr)
            val future = job.enqueue()  // 注意：enqueue 才会返回 Future<Result> 句柄

            // 取消协程时，尝试取消 Future
            continuation.invokeOnCancellation {
                future.cancel(true)
            }

            // 将 Future<Result> 桥接到协程
            val scope = CoroutineScope(continuation.context + Dispatchers.IO)
            scope.launch {
                try {
                    val result = future.get() // 阻塞在 IO 线程
                    if (continuation.isActive) {
                        continuation.resume(CommandOutput(result, stdout, stderr))
                    }
                } catch (t: Throwable) {
                    if (continuation.isActive) {
                        continuation.resumeWithException(t)
                    }
                }
            }
        }
    }
}